<template>
  <view class="warehouse-container">
    <!-- A. 页面头部 -->
    <view class="page-header">
      <text class="page-title">加热炉作业</text>
    </view>

    <!-- B. 主信息区 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业设定</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text
              class="form-label"
              style="margin-right: 20rpx; margin-bottom: 0"
              >生产工序</text
            >
            <picker
              mode="selector"
              :range="processOptions"
              range-key="text"
              :value="currentProcessIndex"
              @change="handleProcessChange"
              class="form-picker"
              style="flex: 1"
            >
              <view class="picker-content">
                <text>{{
                  currentProcess && currentProcess.processName
                    ? currentProcess.processName
                    : "请选择生产工序"
                }}</text>
                <text class="picker-arrow">▼</text>
              </view>
            </picker>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: baseline; flex: 1"
          >
            <text class="form-label" style="margin-right: 10px">班别：</text>
            <text class="form-value">{{ workClass || "未设置" }}</text>
          </view>
          <view
            class="form-group"
            style="
              flex-direction: row;
              align-items: baseline;
              flex: 1;
              margin-left: 20px;
            "
          >
            <text class="form-label" style="margin-right: 10px">班次：</text>
            <text class="form-value">{{ workShift || "未设置" }}</text>
          </view>
        </view>

        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text class="form-label" style="margin-right: 10px">入炉工：</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入入炉工"
              v-model.trim="formData.workStaffIn"
              style="flex: 1"
            />
          </view>
        </view>
        <view class="form-row">
          <view
            class="form-group"
            style="flex-direction: row; align-items: center"
          >
            <text class="form-label" style="margin-right: 10px">出炉工：</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入出炉工"
              v-model.trim="formData.workStaffOut"
              style="flex: 1"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">操作备注</text>
            <input
              type="text"
              class="form-input"
              placeholder="请输入操作备注"
              style="
                border: 1px solid #e0e0e0;
                border-radius: 6px;
                padding: 8px;
                background-color: #fafafa;
                resize: vertical;
                min-height: 60px;
                font-size: 14px;
                line-height: 1.4;
              "
              v-model.trim="formData.busMemo"
            />
          </view>
        </view>
      </view>
    </view>

    <!-- C. 投料作业区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">投料作业</text>
      </view>

      <view class="form-section">
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <!-- 使用统一扫码输入组件 -->
            <ScanInput
              v-model="searchForm.searchCode"
              placeholder="请输入批次号"
              tip-text="支持扫描批次号"
              :loading="false"
              :on-scan-result="handleScanResult"
              :on-confirm="handleScanConfirm"
              ref="scanInputRef"
            />
          </view>
        </view>

        <!-- 批次信息表格 -->
        <view class="table-container">
          <view class="table-body">
            <view class="table-row header">
              <text class="table-cell">批次号</text>
              <text class="table-cell">钢种</text>
              <text class="table-cell">规格</text>
              <text class="table-cell">重量</text>
              <text class="table-cell">数量</text>
              <text class="table-cell">生产日期</text>
            </view>
            <view
              class="table-row"
              v-for="(item, index) in furnaceTable"
              :key="index"
            >
              <text class="table-cell">{{ item.batchNo }}</text>
              <text class="table-cell">{{ item.steelGradeName }}</text>
              <text class="table-cell">{{ item.prodSpec }}</text>
              <text class="table-cell">{{ item.prodCount || 0 }}</text>
              <text class="table-cell">{{ item.transCount || 0 }}</text>
              <text class="table-cell">{{
                dateHelperApi.formatDate(item.inDate)
              }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- D. 产出作业区域 -->
    <view class="plan-form-container">
      <view class="section-header">
        <text class="section-title">作业记录</text>
      </view>

      <!-- 产品下线内容 -->
      <view class="form-section">
        <!-- <view class="form-row">
          <view class="form-group">
            <text class="form-label">炉次号</text>
            <input
              type="text"
              class="form-input"
              placeholder="炉次号"
              v-model.trim="furnaceNoDisplay"
              :disabled="true"
              style="width: 100%"
            />
          </view>
        </view> -->
        <view class="form-row">
          <view class="form-group" style="flex: none; width: 100%">
            <text class="form-label">批次</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <input
                type="text"
                class="form-input"
                placeholder="请点击批次打印自动生成"
                v-model.trim="formData.batchNo"
                style="flex: 1"
              />
              <button class="btn-submit" @click="handlePrintBatch">打印</button>
              <button class="btn-submit" @click="handleCreateBatch">
                拆批
              </button>
            </view>

            <view class="form-row"> </view>
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">钢种</text>
            <input
              type="text"
              class="form-input"
              placeholder="钢种"
              v-model.trim="formData.steelGradeName"
            />
          </view>
          <view class="form-group">
            <text class="form-label">规格</text>
            <input
              type="text"
              class="form-input"
              placeholder="规格"
              v-model.trim="formData.prodSpec"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">投料量</text>
            <input
              type="digit"
              class="form-input"
              placeholder="请输入投料量"
              v-model.number="formData.costWg"
              @input="validateNumber($event, formData, 'costWg')"
            />
          </view>
          <view class="form-group">
            <text class="form-label">投料支数</text>
            <input
              type="number"
              class="form-input"
              placeholder="请输入投料支数"
              v-model.number="formData.costCount"
              @input="validateNumber($event, formData, 'costCount')"
            />
          </view>
        </view>

        <view class="form-row">
          <view class="form-group">
            <text class="form-label">入炉时间</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <picker
                mode="multiSelector"
                :range="dateTimePickerRange"
                :value="batchBeginPickerIndex"
                @change="handleBatchBeginChange"
                class="form-picker"
                style="flex: 1"
              >
                <view class="picker-content">
                  <text>{{ formData.batchBegin || "入炉时间" }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
              <button
                class="btn-select btn-sm"
                @click="setCurrentDateTime('batchBegin')"
              >
                确认
              </button>
            </view>
          </view>

          <view class="form-group">
            <text class="form-label">点火时间</text>
            <view style="display: flex; align-items: center; gap: 8px">
              <picker
                mode="multiSelector"
                :range="dateTimePickerRange"
                :value="furnaceBeginPickerIndex"
                @change="handleFurnaceBeginChange"
                class="form-picker"
                style="flex: 1"
              >
                <view class="picker-content">
                  <text>{{ formData.furnaceBegin || "点火时间" }}</text>
                  <text class="picker-arrow">▼</text>
                </view>
              </picker>
              <button
                class="btn-select btn-sm"
                @click="setCurrentDateTime('furnaceBegin')"
              >
                确认
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- D. 按钮操作区 -->
      <view class="button-row">
        <button class="btn-reset" @click="handleReset">重置</button>
        <button class="btn-submit" @click="handleOffline">保存</button>
      </view>
    </view>
  </view>
</template>

<script>
// 导入API方法
import { getProcessOptions } from "@/api/md/process";
import { LzProdStockRealApi } from "@/api/warehouse/lzprodstockreal";
import { ZgRecordFurnaceApi } from "@/api/lz/zgrecordfurnace";

// 导入统一扫码输入组件
import ScanInput from "@/components/ScanInput";

import { dateHelperApi, formatDateTime } from "@/pages/smart/utils/date-helper";
import { pdaScanApi } from "@/pages/smart/pdaScan";
export default {
  name: "StockIn",
  mixins: [pdaScanApi],
  components: {
    ScanInput,
  },

  data() {
    return {
      // 时间选择器索引
      batchBeginPickerIndex: [0, 0, 0, 0, 0, 0],
      batchEndPickerIndex: [0, 0, 0, 0, 0, 0],
      furnaceBeginPickerIndex: [0, 0, 0, 0, 0, 0],
      furnaceEndPickerIndex: [0, 0, 0, 0, 0, 0],
      // 表单数据
      formData: {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: "",
        processName: "",
        // 基础字段
        furnaceNo: "", // 炉次号
        operationMemo: "", // 操作备注
        workStaff: "", // 配渣工
        // 投料作业字段
        costWg: "", // 钢棒重量
        costCount: "", // 钢棒支数
        // 产出作业字段
        batchNo: "", // 批次号
        steelGradeName: "", // 钢种
        prodSpec: "", // 规格

        // 时间相关字段
        costMeth: "", // 转料方式
        batchBegin: "", // 入炉时间
        batchEnd: "", // 出炉时间
        furnaceBegin: "", // 点火时间
        furnaceEnd: "", // 停火时间
      },
      // 扫码查询表单
      searchForm: {
        searchCode: "", // 扫码内容
      },
      // 扫码加载状态（已取消）
      scanLoading: false,

      // 当前工序信息
      currentProcess: {
        processCode: "",
        processName: "请选择生产工序",
      },
      // 班次班组信息
      workShift: "", // 班次
      workClass: "", // 班组

      // 工序选项列表
      processOptions: [],
      // 当前工序索引
      currentProcessIndex: -1,
      // 炉次信息表格数据
      furnaceTable: [],
      // 炉次号显示
      furnaceNoDisplay: "",
      // 表格是否可编辑
      isTableEditable: true,
      // 转料方式选项
      transferMethods: ["天车", "叉车", "输送带", "其他"],
    };
  },
  computed: {
    // 日期工具命名空间（供模板使用）
    dateHelperApi() {
      return dateHelperApi;
    },
    // 时间选择器范围
    dateTimePickerRange() {
      const years = [];
      const months = [];
      const days = [];
      const hours = [];
      const minutes = [];
      const seconds = [];

      // 生成年份范围（2020-2030）
      for (let i = 2020; i <= 2030; i++) {
        years.push(i.toString());
      }

      // 生成月份范围（1-12）
      for (let i = 1; i <= 12; i++) {
        months.push(i.toString().padStart(2, "0"));
      }

      // 生成日期范围（1-31）
      for (let i = 1; i <= 31; i++) {
        days.push(i.toString().padStart(2, "0"));
      }

      // 生成小时范围（0-23）
      for (let i = 0; i <= 23; i++) {
        hours.push(i.toString().padStart(2, "0"));
      }

      // 生成分钟范围（0-59）
      for (let i = 0; i <= 59; i++) {
        minutes.push(i.toString().padStart(2, "0"));
      }

      // 生成秒范围（0-59）
      for (let i = 0; i <= 59; i++) {
        seconds.push(i.toString().padStart(2, "0"));
      }

      return [years, months, days, hours, minutes, seconds];
    },
  },
  async onLoad() {
    await this.loadProcessOptions(); // 加载工序选项
    this.loadCurrentProcess(); // 加载当前工序
    // 初始化PDA打印模块（来自mixin）
    this.initScanModule();
  },
  beforeDestroy() {
    // 停止PDA扫码，释放资源（来自mixin）
    this.stopPdaScan();
  },
  methods: {
    // 扫码结果处理
    handleScanResult(result) {
      // 预处理扫码结果
      if (result && result.length > 0) {
        this.searchForm.searchCode = result;
        this.handleScanConfirm();
      }
    },

    // 扫码确认查询
    async handleScanConfirm() {
      if (!this.searchForm.searchCode.trim()) {
        uni.showToast({
          title: "请输入批次号",
          icon: "none",
        });
        return;
      }

      try {
        // 根据扫码内容判断查询类型并调用相应接口
        const searchCode = this.searchForm.searchCode.trim();

        // 调用批次号查询接口
        const params = {
          batchNo: searchCode,
          pageNum: 1,
          processName: "提纯",
          pageSize: 100,
        };

        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );

        if (response.code === 0 && response.data.list.length > 0) {
          // 使用warehouseCode作为入炉时间，已经是正确格式的时间字符串
          this.formData.batchBegin = response.data.list[0].warehouseCode || "";
          // 使用warehouseName作为点火时间，已经是正确格式的时间字符串
          this.formData.furnaceBegin =
            response.data.list[0].warehouseName || "";

          // 将查询结果转换为furnaceTable格式
          this.furnaceTable = response.data.list.map((item) => ({
            id: item.id,
            batchNo: item.batchNo,
            steelGradeName: item.steelGradeName,
            prodSpec: item.prodSpec,
            prodCount: item.scrapWg || "",
            transCount: item.scrapCount || "",
            inDate:
              item.inDate || item.prodDate || dateHelperApi.getCurrentDate(),
            furnaceNo: item.furnaceNo || "",
          }));
          //- 将查询结果的第一行数据赋值到表单对应字段
          // - 添加了炉次号显示字段和默认值处理
          // - 包含字段：炉次号、批次号、钢种、规格、投料量、投料支数
          if (this.furnaceTable.length > 0) {
            const firstItem = this.furnaceTable[0];
            this.formData.furnaceNo = firstItem.furnaceNo || "";
            this.formData.batchNo = firstItem.batchNo || "";
            this.formData.steelGradeName = firstItem.steelGradeName || "";
            this.formData.prodSpec = firstItem.prodSpec || "";
            this.formData.costWg = firstItem.prodCount || "";
            this.formData.costCount = firstItem.transCount || "";
            this.furnaceNoDisplay = firstItem.furnaceNo || "";

            // 初始化时间选择器索引
            console.log("初始化时间选择器:", {
              batchBegin: this.formData.batchBegin,
              furnaceBegin: this.formData.furnaceBegin,
            });

            if (this.formData.batchBegin) {
              this.batchBeginPickerIndex = this.dateTimeStringToIndex(
                this.formData.batchBegin
              );
            }
            if (this.formData.furnaceBegin) {
              this.furnaceBeginPickerIndex = this.dateTimeStringToIndex(
                this.formData.furnaceBegin
              );
            }
          }

          uni.showToast({
            title: `查询成功，共${this.furnaceTable.length}条记录`,
            icon: "success",
          });
        } else {
          this.furnaceTable = [];
          // 清空表单数据
          this.formData = {
            ...this.formData,
            furnaceNo: "",
            batchNo: "",
            steelGradeName: "",
            prodSpec: "",
            costWg: "",
            costCount: "",
            batchBegin: "", //入炉时间
            furnaceBegin: "", //点火时间
          };
          this.furnaceNoDisplay = "";
          uni.showToast({
            title: "未查询到相关批次信息",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("批次号查询失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
      }
    },

    /* 加载当前工序 */
    loadCurrentProcess() {
      // 尝试从用户配置中加载缓存的工序信息
      const userData = this.$store.state.user;
      const userConfig = userData.userConfig || {};
      if (userData && userData.userConfig) {
        const userConfig = userData.userConfig;
        // 从缓存中加载工序信息
        if (userConfig.processNo && userConfig.processName) {
          this.currentProcess = {
            processCode: userConfig.processNo,
            processName: userConfig.processName,
          };
          this.formData.processCode = userConfig.processNo;
          this.formData.processName = userConfig.processName;

          // 加载班次班组信息
          this.workShift = userConfig.workShift || "";
          this.workClass = userConfig.workClass || "";

          // 在工序选项中找到对应的索引
          const processIndex = this.processOptions.findIndex(
            (item) => item.value === userConfig.processNo
          );
          if (processIndex !== -1) {
            this.currentProcessIndex = processIndex;
          }
          return;
        }
      }

      // 如果没有缓存或缓存无效，默认选择第一个工序
      if (this.processOptions.length > 0) {
        this.currentProcess = {
          processCode: this.processOptions[0].value,
          processName: this.processOptions[0].text,
        };
        this.formData.processCode = this.currentProcess.processCode;
        this.formData.processName = this.currentProcess.processName;
        this.currentProcessIndex = 0;
      }
    },

    // 加载工序选项
    async loadProcessOptions() {
      try {
        const options = await getProcessOptions();
        this.processOptions = options;
        console.log("生产工序选项加载成功:", this.processOptions);
      } catch (error) {
        // 静默处理错误
        console.error("加载工序选项失败:", error);
        this.processOptions = [];
      }
    },

    /* 处理工序选择变化 */
    handleProcessChange(e) {
      const index = e.detail.value;
      this.currentProcessIndex = index;
      const selectedProcess = this.processOptions[index];
      if (selectedProcess) {
        this.currentProcess = {
          processCode: selectedProcess.value,
          processName: selectedProcess.text,
        };
        this.formData.processCode = selectedProcess.value;
        this.formData.processName = selectedProcess.text;
      }
    },

    // 打印测试
    async testPdaPrint() {
      try {
        console.log("开始打印测试...");

        const result = this.pdaPrint(
          "B20251019",
          "测试备注1",
          "备注2",
          "备注3"
        );

        if (result) {
          this.$modal.alert({
            content: "打印成功",
            title: "提示",
          });
        } else {
          this.$modal.alert({
            content: "打印失败，请检查打印机状态",
            title: "错误",
          });
        }
      } catch (error) {
        console.error("打印测试异常:", error);
        this.$modal.alert({
          content: "打印测试异常：" + error.message,
          title: "错误",
        });
      }
    },

    // 扫码查询炉次号
    handleScanFurnaceNo() {
      // 调用扫码功能
      pdaScanApi
        .scan()
        .then((result) => {
          if (result.success) {
            this.formData.furnaceNo = result.content;
            uni.showToast({
              title: "扫码成功",
              icon: "success",
            });

            // 模拟查询炉次信息（实际项目中应调用API）
            this.queryFurnaceInfo(result.content);
          } else {
            uni.showToast({
              title: "扫码失败",
              icon: "none",
            });
          }
        })
        .catch((error) => {
          console.error("扫码异常:", error);
          uni.showToast({
            title: "扫码异常",
            icon: "none",
          });
        });
    },

    // 查询炉次信息
    queryFurnaceInfo(furnaceNo) {
      // 模拟查询结果（实际项目中应调用API）
      const mockData = {
        furnaceNo: furnaceNo,
        steelGradeName: "HRB400E",
        inDate: "2024-01-15",
      };

      // 检查是否已存在相同炉次号
      const existingIndex = this.furnaceTable.findIndex(
        (item) => item.furnaceNo === furnaceNo
      );

      if (existingIndex === -1) {
        // 添加到表格
        this.furnaceTable.push(mockData);
        uni.showToast({
          title: "炉次信息已添加",
          icon: "success",
        });
      } else {
        // 更新现有记录
        this.furnaceTable.splice(existingIndex, 1, mockData);
        uni.showToast({
          title: "炉次信息已更新",
          icon: "success",
        });
      }
    },

    // 拆批
    async handleCreateBatch() {
      // 校验是否存在炉次号
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先输入炉次号",
          icon: "none",
        });
        return;
      }

      try {
        // 准备创建批次的参数
        const createData = {
          furnaceNo: this.formData.furnaceNo,
          batchNo: this.formData.batchNo,
          // 其他必要字段可以根据实际需求添加
          processNo: this.currentProcess.processCode,
          processName: this.currentProcess.processName,
          ywDate: this.formData.currentDate,
          workShift: this.$store.state.user.userConfig?.workShift || "",
          wortkType: this.$store.state.user.userConfig?.workClass || "",
          workStaff: this.formData.workStaff || "",
          busMemo: this.formData.busMemo + "（拆批）:" + this.formData.batchNo,
        };

        console.log("拆批参数:", createData);

        // 调用创建批次API（使用加热炉的API）
        const response = await ZgRecordFurnaceApi.createZgRecordFurnace(
          createData
        );

        if (response.code === 0) {
          // 从响应中获取新批次号
          if (response.data && response.data.batchNo) {
            this.formData.batchNo = response.data.batchNo;
            // 清空投料量和投料支数
            this.formData.costWg = "";
            this.formData.costCount = "";
          }

          uni.showToast({
            title: "拆批成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: response.msg || "拆批失败",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("拆批失败:", error);
        uni.showToast({
          title: "拆批失败，请重试",
          icon: "none",
        });
      }
    },
    async handleBatchQuery() {
      try {
        // 显示加载中
        uni.showLoading({
          title: "查询中...",
        });

        // 调用批量查询API
        const params = {
          pageNum: 1,
          pageSize: 50, // 批量查询显示更多数据
          processName: "加热",
          batchNo: this.formData.batchNo,
          // 可以根据需要添加更多查询条件
        };

        const response = await LzProdStockRealApi.getLzProdStockRealPage(
          params
        );

        uni.hideLoading();

        if (response.code === 0) {
          // 将分页查询返回的第一行数据分别赋值给formData的字段中
          if (
            response.data &&
            response.data.list &&
            response.data.list.length > 0
          ) {
            const firstRow = response.data.list[0];

            // 将查询结果的第一行数据赋值到表单对应字段
            this.furnaceNoDisplay = firstRow.furnaceNo || "";
            this.formData.furnaceNo = firstRow.furnaceNo || "";
            this.formData.batchNo = firstRow.batchNo || "";
            this.formData.steelGradeName = firstRow.steelGradeName || "";
            this.formData.steelGradeCode = firstRow.steelGradeCode || "";
            this.formData.prodSpec = firstRow.prodSpec || "";
            this.formData.costWg = firstRow.prodCount || 0;
            this.formData.costCount = firstRow.transCount || 0;
            this.formData.standCode = firstRow.standCode || "";
            this.formData.standNo = firstRow.standNo || "";
            this.formData.materialCode = firstRow.materialCode || "";
            this.formData.materialName = firstRow.materialName || "";
            this.formData.planNo = firstRow.planNo || "";
            this.formData.planId = firstRow.planId || "";
            this.formData.planCount = firstRow.planCount || "";

            uni.showToast({
              title: "批次查询成功",
              icon: "success",
            });
          } else {
            uni.showToast({
              title: "未查询到批次信息",
              icon: "none",
            });
          }
        } else {
          uni.showToast({
            title: response.msg || "查询失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("批次查询失败:", error);
        uni.showToast({
          title: "查询失败，请重试",
          icon: "none",
        });
      }
    },

    // 批次打印
    async handlePrintBatch() {
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先创建批次",
          icon: "none",
        });
        return;
      }

      try {
        console.log("批次打印参数:", {
          batchNo: this.formData.batchNo,
          steelGradeName: this.formData.steelGradeName,
          printTime: dateHelperApi.getCurrentDate(),
        });

        // 调用PDA打印接口
        const printResult = this.pdaPrint(
          this.formData.batchNo, // 批次号
          this.formData.steelGradeName + "/" + this.formData.prodSpec || "", // 规格
          dateHelperApi.getCurrentDate() // 打印时间
        );

        if (printResult) {
          uni.showToast({
            title: "批次打印成功",
            icon: "success",
          });
        } else {
          uni.showToast({
            title: "批次打印失败，请检查设备",
            icon: "none",
          });
        }
      } catch (error) {
        console.error("批次打印失败:", error);
        uni.showToast({
          title: "批次打印失败，请重试",
          icon: "none",
        });
      }
    },

    // 表格滚动到底部加载更多
    onReachBottom() {
      // 数据加载功能已取消
    },

    // 数字验证
    validateNumber(event, obj, field) {
      const value = parseFloat(event.detail.value);
      if (isNaN(value) || value < 0) {
        obj[field] = "";
        uni.showToast({
          title: "请输入有效的数字",
          icon: "none",
        });
      } else {
        obj[field] = value;
      }
    },

    // 投料删除
    handleInputDelete() {
      // 数据加载功能已取消
      uni.showToast({
        title: "投料删除功能已取消",
        icon: "none",
      });
    },

    // 投料确定
    async handleInputSubmit() {
      // 校验furnaceTable表格数据
      if (!this.furnaceTable || this.furnaceTable.length === 0) {
        uni.showToast({
          title: "请先添加投料信息",
          icon: "none",
        });
        return;
      }

      // 获取第一行数据进行投料处理
      const firstItem = this.furnaceTable[0];

      // 显示投料重量确认对话框
      const confirmed = await this.showCostWeightConfirm(firstItem);
      if (!confirmed) {
        return; // 用户取消投料
      }

      // 显示加载中提示
      uni.showLoading({
        title: "投料处理中...",
        mask: true,
      });

      try {
        // 构建投料数据
        const onlineData = {
          furnaceNo: firstItem.furnaceNo,
          batchNo: firstItem.batchNo,
          // 其他必要字段
          processNo: this.currentProcess.processCode,
          processName: this.currentProcess.processName,
          steelGradeCode: firstItem.steelGradeCode || "",
          steelGradeName: firstItem.steelGradeName || "",
          standCode: firstItem.standCode || "",
          standNo: firstItem.standNo || "",
          // 补充业务字段
          planNo: this.formData.planNo || "",
          ywDate: this.formatDateTime(
            this.formData.currentDate || formatDateTime(new Date(), "end")
          ),
          workShift: this.$store.state.user.userConfig?.workShift || "",
          wortkType: this.$store.state.user.userConfig?.workClass || "",
          workStaff: this.formData.workStaff || "",
          busMemo: this.formData.operationMemo || "",
        };

        // 调用投料API
        const response = await ZgRecordFurnaceApi.onlineJrRecord(onlineData);

        // 隐藏加载中提示
        uni.hideLoading();

        if (response.code === 0) {
          // 投料成功
          uni.showToast({
            title: "投料成功",
            icon: "success",
            duration: 2000,
          });

          // 清空投料表格
          this.furnaceTable = [];
        } else {
          // 投料失败，显示错误信息
          uni.showToast({
            title: response.msg || "投料失败",
            icon: "none",
            duration: 3000,
          });
        }
      } catch (error) {
        // 隐藏加载中提示
        uni.hideLoading();

        console.error("投料API调用失败:", error);

        // 显示错误信息
        uni.showToast({
          title: "投料失败，请重试",
          icon: "none",
          duration: 3000,
        });
      }
    },

    // 显示投料重量确认对话框
    showCostWeightConfirm(firstItem) {
      return new Promise((resolve) => {
        const weight = firstItem.prodCount || 0;
        const count = firstItem.transCount || 0;
        const content = `投料重量：${weight}KG\n投料数量：${count}件\n\n请确认投料信息是否正确？`;

        uni.showModal({
          title: "投料重量确认",
          content: content,
          confirmText: "确认投料",
          cancelText: "取消",
          success: (res) => {
            resolve(res.confirm);
          },
          fail: () => {
            resolve(false);
          },
        });
      });
    },

    // 设置当前日期时间
    setCurrentDateTime(field) {
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0");
      const day = String(now.getDate()).padStart(2, "0");
      const hours = String(now.getHours()).padStart(2, "0");
      const minutes = String(now.getMinutes()).padStart(2, "0");
      this.formData[field] = `${year}-${month}-${day} ${hours}:${minutes}`;

      // 更新对应的picker索引
      const yearIndex = year - 2020; // 与时间选择器range定义保持一致
      const monthIndex = now.getMonth();
      const dayIndex = now.getDate() - 1;
      const hourIndex = now.getHours();
      const minuteIndex = now.getMinutes();
      const secondIndex = now.getSeconds();

      if (field === "batchBegin") {
        this.batchBeginPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      } else if (field === "batchEnd") {
        this.batchEndPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      } else if (field === "furnaceBegin") {
        this.furnaceBeginPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      } else if (field === "furnaceEnd") {
        this.furnaceEndPickerIndex = [
          yearIndex,
          monthIndex,
          dayIndex,
          hourIndex,
          minuteIndex,
          secondIndex,
        ];
      }
    },

    // 将日期时间字符串转换为选择器索引
    dateTimeStringToIndex(dateTimeStr) {
      const startYear = 2020; // 与时间选择器range定义保持一致

      if (!dateTimeStr) {
        const now = new Date();
        return [
          now.getFullYear() - startYear, // 年份索引（相对于起始年份）
          now.getMonth(), // 月份索引（0-11）
          now.getDate() - 1, // 日期索引（0-30）
          now.getHours(), // 小时索引（0-23）
          now.getMinutes(), // 分钟索引（0-59）
          now.getSeconds(), // 秒索引（0-59）
        ];
      }

      try {
        const [datePart, timePart] = dateTimeStr.split(" ");
        const [year, month, day] = datePart.split("-").map(Number);
        const [hours, minutes, seconds] = timePart.split(":").map(Number);

        return [
          year - startYear, // 年份索引
          month - 1, // 月份索引（0-11）
          day - 1, // 日期索引（0-30）
          hours, // 小时索引（0-23）
          minutes, // 分钟索引（0-59）
          seconds, // 秒索引（0-59）
        ];
      } catch (error) {
        console.error("日期时间转换失败:", error);
        const now = new Date();
        return [
          now.getFullYear() - startYear,
          now.getMonth(),
          now.getDate() - 1,
          now.getHours(),
          now.getMinutes(),
          now.getSeconds(),
        ];
      }
    },

    // 将选择器索引转换为日期时间字符串
    indexToDateTimeString(indexes) {
      const [
        yearIndex,
        monthIndex,
        dayIndex,
        hourIndex,
        minuteIndex,
        secondIndex,
      ] = indexes;
      const startYear = 2020; // 与时间选择器range定义保持一致

      const year = startYear + yearIndex;
      const month = String(monthIndex + 1).padStart(2, "0");
      const day = String(dayIndex + 1).padStart(2, "0");
      const hour = String(hourIndex).padStart(2, "0");
      const minute = String(minuteIndex).padStart(2, "0");
      const second = String(secondIndex).padStart(2, "0");

      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },

    // 处理时间选择器变化
    handleBatchBeginChange(e) {
      const indexes = e.detail.value;
      this.batchBeginPickerIndex = indexes;
      this.formData.batchBegin = this.indexToDateTimeString(indexes);
    },

    handleBatchEndChange(e) {
      const indexes = e.detail.value;
      this.batchEndPickerIndex = indexes;
      this.formData.batchEnd = this.indexToDateTimeString(indexes);
    },

    handleFurnaceBeginChange(e) {
      const indexes = e.detail.value;
      this.furnaceBeginPickerIndex = indexes;
      this.formData.furnaceBegin = this.indexToDateTimeString(indexes);
    },

    handleFurnaceEndChange(e) {
      const indexes = e.detail.value;
      this.furnaceEndPickerIndex = indexes;
      this.formData.furnaceEnd = this.indexToDateTimeString(indexes);
    },
    // 重置表单
    handleReset() {
      this.furnaceNoDisplay = "";
      this.formData = {
        currentDate: dateHelperApi.getCurrentDate(),
        processCode: this.formData.processCode,
        processName: this.formData.processName,

        searchForm: {
          searchCode: "",
        },
        // 基础字段
        furnaceNo: "",
        operationMemo: "",
        workStaff: "",
        // 投料作业字段
        costWg: "",
        costCount: "",
        // 产出作业字段
        batchNo: "",
        qaWg: "",
        qaCount: "",

        // 时间相关字段
        costMeth: "",
        batchBegin: "",
        batchEnd: "",
        furnaceBegin: "",
        furnaceEnd: "",

        //清空投料表格
        furnaceTable: [],
        //清空查询条件
        batchNo: "",
        steelGradeName: "",
        prodSpec: "",
      };
      uni.showToast({
        title: "表单已刷新",
        icon: "success",
      });
    },

    // 格式化日期时间为YYYY-MM-DD HH:mm:ss格式
    formatDateTime(dateStr) {
      if (!dateStr) return "";
      // 检查是否已经包含秒数
      if (dateStr.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}/)) {
        return dateStr;
      }
      // 检查是否包含时分
      if (dateStr.match(/\d{4}-\d{2}-\d{2} \d{2}:\d{2}/)) {
        return `${dateStr}:00`;
      }
      // 只有日期，没有时间
      if (dateStr.match(/\d{4}-\d{2}-\d{2}/)) {
        return `${dateStr} 00:00:00`;
      }
      // 其他情况返回原字符串
      return dateStr;
    },

    // 下线保存
    async handleOffline() {
      // 先判断炉次号是否为空
      if (!this.formData.furnaceNo) {
        uni.showToast({
          title: "请先扫码查询并确认炉次信息",
          icon: "none",
        });
        return;
      }

      // 执行投料确定逻辑
      // 校验furnaceTable表格数据
      if (!this.furnaceTable || this.furnaceTable.length === 0) {
        uni.showToast({
          title: "请先添加投料信息",
          icon: "none",
        });
        return;
      }

      // 获取第一行数据进行投料处理
      const firstItem = this.furnaceTable[0];

      // 显示投料重量确认对话框
      const confirmed = await this.showCostWeightConfirm(firstItem);
      if (!confirmed) {
        return; // 用户取消投料
      }

      // 检查批次号是否为空
      if (!this.formData.batchNo) {
        uni.showToast({
          title: "请先选择批次号",
          icon: "none",
        });
        return;
      }

      // 显示加载中提示
      uni.showLoading({
        title: "处理中...",
        mask: true,
      });

      try {
        // 构建投料数据
        const onlineData = {
          furnaceNo: firstItem.furnaceNo,
          batchNo: firstItem.batchNo,
          // 其他必要字段
          processNo: this.currentProcess.processCode,
          processName: this.currentProcess.processName,
          steelGradeCode: firstItem.steelGradeCode || "",
          steelGradeName: firstItem.steelGradeName || "",
          standCode: firstItem.standCode || "",
          standNo: firstItem.standNo || "",
          // 补充业务字段
          planNo: this.formData.planNo || "",
          ywDate: this.formData.currentDate || dateHelperApi.getCurrentDate(),
          workShift: this.$store.state.user.userConfig?.workShift || "",
          wortkType: this.$store.state.user.userConfig?.workClass || "",
          workStaff: this.formData.workStaff || "",
          busMemo: this.formData.operationMemo || "",
        };

        // 调用投料API
        const onlineResponse = await ZgRecordFurnaceApi.onlineJrRecord(
          onlineData
        );

        if (onlineResponse.code !== 0) {
          // 投料失败
          uni.hideLoading();
          uni.showToast({
            title: onlineResponse.msg || "投料失败",
            icon: "none",
            duration: 3000,
          });
          return;
        }

        // 构建下线数据
        const offlineData = {
          planNo: this.formData.planNo || "", // 计划号
          batchNo: this.formData.batchNo, // 批次号
          steelGradeName: this.formData.steelGradeName || "", // 钢种
          prodSpec: this.formData.prodSpec || "", // 规格
          furnaceNo: this.formData.furnaceNo, // 炉次号
          qmAmount: Number(this.formData.qaWg) || 0, // 钢棒重量
          costWg: Number(this.formData.costWg) || 0, // 投料重量
          costCount: Number(this.formData.costCount) || 0, // 投料数量
          costMeth: this.formData.costMeth || "", // 投料方式

          ywDate: this.formatDateTime(this.formData.currentDate || ""), // 业务日期
          processName: this.formData.processName, // 工序名称
          workShift: this.$store.state.user.userConfig?.workShift || "", // 班次
          wortkType: this.$store.state.user.userConfig?.workClass || "", // 班别
          workStaff: this.formData.workStaff || "", // 操作工
          busMemo: this.formData.busMemo || "", // 备注
          batchBegin: this.formatDateTime(this.formData.batchBegin || ""), // 入炉时间
          batchEnd: this.formatDateTime(this.formData.batchEnd || ""), // 出炉时间
          furnaceBegin: this.formatDateTime(this.formData.furnaceBegin || ""), // 点火时间
          furnaceEnd: this.formatDateTime(this.formData.furnaceEnd || ""), // 停火时间
        };

        // 调用下线API
        const response = await ZgRecordFurnaceApi.offlineJrRecord(offlineData);

        uni.hideLoading();

        if (response.code === 0) {
          uni.showToast({
            title: "保存成功",
            icon: "success",
            duration: 2000,
          });

          // 成功后重置表单
          this.handleReset();
        } else {
          uni.showToast({
            title: response.msg || "保存失败",
            icon: "none",
          });
        }
      } catch (error) {
        uni.hideLoading();
        console.error("下线处理失败:", error);
        uni.showToast({
          title: "保存失败，请重试",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss">
@import "~@/pages/smart/scss/create.scss";

// picker组件样式
.form-picker {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  padding: 8px;
  background-color: #fafafa;
  cursor: pointer;

  .picker-content {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .picker-arrow {
      color: #999;
      font-size: 12px;
    }

    .btn-confirm-time {
      background-color: #1890ff;
      color: white;
      border: none;
      border-radius: 4px;
      padding: 8px 12px;
      font-size: 12px;
      white-space: nowrap;
      cursor: pointer;
      transition: background-color 0.3s;
    }

    .btn-confirm-time:hover {
      background-color: #40a9ff;
    }

    .btn-confirm-time:active {
      background-color: #096dd9;
    }
  }
}
</style>
